var express = require('express');
var app = express();

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();

var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;


var socketI;
io.on('connection', function(socket) {
  console.log('新加入');
  socket.on('chat message', function(msg) {
    io.emit('chat message', msg);
  });
  socket.on('login',function(uid){
    // 判断是否已经在房间中
    if(socket.status){
      return;
    }
    socket.join(uid, function(){
      // console.log(socket.rooms); // [ <socket.id>, 'room 237' ]
      socket.status=true;
    });
  })
});

app.post('/post', multipartMiddleware, function(req, res) {
  var req = req.body;
  if (req.event == 'chat message') {
    if(req.uid){
      io.to(req.uid).emit(req.event, req.info);
    }else{
      io.emit(req.event, req.info);
    }
  }

  res.send('ok');
});

http.listen(port, function() {
  console.log('listening on *:' + port);
});
